package com.mengxuegu.blog.oauth2.service;

import com.mengxuegu.blog.entities.SysMenu;
import com.mengxuegu.blog.entities.SysUser;
import com.mengxuegu.blog.feign.IFeignSystemController;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private IFeignSystemController iFeignSystemController;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        if(StringUtils.isEmpty(username)){
            throw new BadCredentialsException("用户名不能为空");
        }
        SysUser userByUsername = iFeignSystemController.findUserByUsername(username);
        if(userByUsername == null){
            throw new BadCredentialsException("用户名密码错误");
        }
        List<SysMenu> menuListByUserId = iFeignSystemController.findMenuListByUserId(userByUsername.getId());
        List<GrantedAuthority> authorities = null;
        if(CollectionUtils.isNotEmpty(menuListByUserId)){
            authorities=new ArrayList<>();
            for (SysMenu sysMenu : menuListByUserId) {
                String code = sysMenu.getCode();
                authorities.add(new SimpleGrantedAuthority(code));
            }
        }
//        String uid, String username, String password,
//                String nickName, String imageUrl, String mobile, String email,
//                Integer isAccountNonExpired, Integer isAccountNonLocked,
//                Integer isCredentialsNonExpired, Integer isEnabled,
//                List<GrantedAuthority> authorities
        JwtUser jwtUser=new JwtUser(userByUsername.getId(),userByUsername.getUsername(),userByUsername.getPassword()
                ,userByUsername.getNickName(),userByUsername.getImageUrl(),userByUsername.getMobile()
                ,userByUsername.getEmail(),userByUsername.getIsAccountNonExpired()
                ,userByUsername.getIsAccountNonLocked(),userByUsername.getIsCredentialsNonExpired()
                ,userByUsername.getIsEnabled(),authorities);
        return jwtUser;
    }
}
